package com.ffyc.cms.controller;

import com.ffyc.cms.common.CommonResult;
import com.ffyc.cms.dao.WriterDao;
import com.ffyc.cms.model.Admin;
import com.ffyc.cms.model.Journalism;
import com.ffyc.cms.model.Newstype;
import com.ffyc.cms.service.WriterService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 写新闻的控制类
 */
@RestController
@RequestMapping(path = "writer")
public class WriterController {
    @Autowired
    WriterService writerService;

    /**
     * 上传封面
     * @param file
     * @param session
     * @return
     */
    @PostMapping(path = "/fileUpload")
    public CommonResult fileUpload(@RequestParam("fileName") CommonsMultipartFile file , HttpSession session){
        CommonResult commonResult = null;
        Admin admin = (Admin)session.getAttribute("admin");
        File f0 = new File("C:\\userImg\\"+admin.getAccount());
        if (!f0.exists()){
            f0.mkdir();
        }
        String oldFileName = file.getOriginalFilename();
        File f1 = new File(f0,oldFileName);//输出路径
        Map map = new HashMap();
        oldFileName = admin.getAccount()+"/"+oldFileName;
        try {
            file.transferTo(f1);
            commonResult = new CommonResult(200,"上传成功",oldFileName);
        } catch (IOException e) {
            e.printStackTrace();
            commonResult = new CommonResult(500,"上传失败",null);
        }
        return commonResult;
    }

    @RequestMapping(path = "savenews")
    public CommonResult savenews(Journalism journalism, HttpSession session, HttpServletRequest req){
        CommonResult commonResult;
        Admin admin = (Admin)session.getAttribute("admin");
        Newstype newstype = new Newstype();
        String newsid =req.getParameter("journame");
        newstype.setId(Integer.valueOf(newsid));
        journalism.setNewstype(newstype);
        journalism.setWriter(admin);
        try {
            writerService.savenews(journalism);
            commonResult = new CommonResult(200,"操作成功",null);
            return commonResult;
        }catch (Exception e){
            e.printStackTrace();
            commonResult = new CommonResult(500,"服务器忙，请稍后重试！",null);
            return commonResult;
        }
    }

}
